package bb.lanxing.activity;

import android.os.Build;
import android.text.Html;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.databinding.ActivityHeartrateSectionSettingBinding;
import bb.lanxing.manager.RemoteSharedPreference;
import bb.lanxing.manager.SPConstant;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.User;
import bb.lanxing.model.json.UserSettings;
import bb.lanxing.mvvm.base.BaseDBActivity;
import bb.lanxing.mvvm.sportsetting.SportSettingViewModel;
import bb.lanxing.mvvm.sportsetting.UserSportSetting;
import bb.lanxing.util.SectionParseUtil;
import bb.lanxing.util.ui.InputHelper;
import bb.lanxing.view.BiciAlertDialogBuilder;
import org.apache.commons.cli.HelpFormatter;

public class HeartrateSectionSettingActivity extends BaseDBActivity<ActivityHeartrateSectionSettingBinding> {
    final static private String TAG = "HeartrateSectionSettingActivity";
    ActivityHeartrateSectionSettingBinding sectionSettingBinding;
    private int[] sections = null;
    SportSettingViewModel viewModel = new SportSettingViewModel(App.getContext());
    private boolean isLoacalNoData = true;
    private int alertValue = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_heartrate_section_setting;
    }

    @Override
    public void initView(ActivityHeartrateSectionSettingBinding binding) {
        sectionSettingBinding = binding;
        setupActionBar(true);
        initData(getIntent().getIntExtra(DeviceSettingsActivity.EXTRA_HEARTRATE_ALERT, 0),
                getIntent().getStringExtra(DeviceSettingsActivity.EXTRA_HEARTRATE_SEGMENT));
        initView();
    }

    private void initView() {
        boolean z = RemoteSharedPreference.getInstance().getBoolean(SPConstant.KEY_TTS_HEART_WARNING_ENABLE, false);
        RelativeLayout relativeLayout = sectionSettingBinding.warningValueLayout;
        if (z) {
            relativeLayout.setVisibility(View.VISIBLE);
        } else {
            relativeLayout.setVisibility(View.GONE);
        }


        sectionSettingBinding.warningSwitch.setChecked(z);

        sectionSettingBinding.warningSwitch.setOnCheckedChangeListener((compoundButton, z2) -> {
            sectionSettingBinding.warningValueLayout.setVisibility(z2 ? View.VISIBLE : View.GONE);
            RemoteSharedPreference.getInstance().setValue(SPConstant.KEY_TTS_HEART_WARNING_ENABLE, z2);
        });
        sectionSettingBinding.learnHeartRateZone.setOnClickListener(this::showZoneInfo);
        sectionSettingBinding.heartRateZ1.setOnClickListener(v -> showEditDialog(0, String.valueOf(sections[0])));
        sectionSettingBinding.heartRateZ2.setOnClickListener(v -> showEditDialog(1, String.valueOf(sections[1])));
        sectionSettingBinding.heartRateZ3.setOnClickListener(v -> showEditDialog(2, String.valueOf(sections[2])));
        sectionSettingBinding.heartRateZ4.setOnClickListener(v -> showEditDialog(3, String.valueOf(sections[3])));
        sectionSettingBinding.heartRateZ5.setOnClickListener(v -> showEditDialog(4, String.valueOf(sections[4])));
        sectionSettingBinding.heartRateMax.setOnClickListener(v -> showEditDialog(5, String.valueOf(sections[5])));
        sectionSettingBinding.warningUnitView.setOnClickListener(this::setupHeartWarning);

        viewModel.getUpdateSettingResult().observe(this,
                userSportSetting -> toast(R.string.toast_edit_successful));
        updateSectionView();
    }

    @Override
    public void onResume() {
        super.onResume();
        viewModel.getSportSetting(App.getContext().getUserId());
    }

    public void updateSectionView() {
//        int[] iArr = {166, 167, 168, 169, 170, 171};
        for (int length = sections.length - 1; length >= 0; length--) {
            int[] iArr2 = sections;
            int i = iArr2[length];
            if (length == iArr2.length - 1) {
//                sectionSettingBinding.setSectionLevel6(getString(R.string.str_fm_unit_bpm, new Object[]{String.valueOf(i)}));
                sectionSettingBinding.heartRateMax.setText(getString(R.string.str_fm_unit_bpm, String.valueOf(i)));
            } else {
                String string = getString(R.string.mine_section_setting_hr_value, String.valueOf(iArr2[length + 1]), String.valueOf(sections[length]));
                int indexOf = string.indexOf(HelpFormatter.DEFAULT_OPT_PREFIX);
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(ContextCompat.getColor(this, R.color.grey_999999));
                ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(ContextCompat.getColor(this, R.color.grey_666666));
                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(string);
                spannableStringBuilder.setSpan(foregroundColorSpan, 0, indexOf, 33);
                spannableStringBuilder.setSpan(foregroundColorSpan2, indexOf + 1, string.length(), 33);
                switch (length) {
                    case 0 ->
                            sectionSettingBinding.heartRateZ1.setText(spannableStringBuilder);
                    case 1 ->
                            sectionSettingBinding.heartRateZ2.setText(spannableStringBuilder);
                    case 2 ->
                            sectionSettingBinding.heartRateZ3.setText(spannableStringBuilder);
                    case 3 ->
                            sectionSettingBinding.heartRateZ4.setText(spannableStringBuilder);
                    case 4 ->
                            sectionSettingBinding.heartRateZ5.setText(spannableStringBuilder);
                    default -> {
                    }
                }
//                sectionSettingBinding.setVariable(iArr[length - 1], spannableStringBuilder);
            }
        }
    }

    private void updateWarningView(int hearRateAlert) {
        if (hearRateAlert == 0) {
            int heartRateWarningValue = RemoteSharedPreference.getInstance().getHeartRateWarningValue();
            if (heartRateWarningValue != 0) {
                sectionSettingBinding.warningValueView.setText(String.valueOf(heartRateWarningValue));
            }
            alertValue = hearRateAlert;
            return;
        }
        sectionSettingBinding.warningValueView.setText(String.valueOf(hearRateAlert));
        alertValue = hearRateAlert;
    }

    private void initData(int heartRateAlert, String hearrRateSegment) {
        UserSettings userSettings;
        if (hearrRateSegment == null || hearrRateSegment.isEmpty()) {
            hearrRateSegment = SharedManager.getInstance().getHeartrateSectionWithMP();
        }
        int[] parse = SectionParseUtil.parse(hearrRateSegment, 6);
        sections = parse;
        if (parse == null || parse.length == 0) {
            User signinUser = App.getContext().getSigninUser();
            if (signinUser != null && (userSettings = signinUser.getUserSettings()) != null) {
                sections = userSettings.getHeartrateSections();
            }
            if (sections == null) {
                isLoacalNoData = true;
                sections = new int[]{98, 117, 137, 156, 176, 196};//98;117;137;156;176;196
            } else {
                isLoacalNoData = false;
            }
        }
        updateWarningView(heartRateAlert);
    }

    public void showEditDialog(final int i, final String str) {
        View inflate = LayoutInflater.from(this).inflate(R.layout.edittext_view, (ViewGroup) null);
        final EditText editText = inflate.findViewById(R.id.editText);
        editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS | InputType.TYPE_CLASS_NUMBER);
        editText.setMaxLines(1);
        if (TextUtils.isEmpty(str)) {
            editText.setHint(R.string.dialog_hint_input);
        } else {
            editText.setText(str);
        }

        AlertDialog.Builder mSetNegativeButton =
                new BiciAlertDialogBuilder(this)
                        .setView(inflate)
                        .setPositiveButton(R.string.dialog_btn_ok, (dialogInterface, i2) -> {
                            String obj = editText.getText().toString();
                            if (TextUtils.isEmpty(obj) || obj.equals(str)) {
                                dialogInterface.cancel();
                            } else {
                                int parseInt = Integer.parseInt(obj);
                                if (i == -1) {
                                    RemoteSharedPreference.getInstance().setHeartRateWarningValue(parseInt);
                                    sectionSettingBinding.warningValueView.setText(String.valueOf(parseInt));
                                    requestSetting(null, Integer.valueOf(obj));
                                    updateWarningView(parseInt);
                                } else {
                                    updateSections(i, Math.abs(parseInt));
                                    String makeSectionString = makeSectionString(sections);
                                    SharedManager.getInstance().setHeartrateSectionWithMP(makeSectionString);
                                    updateSectionView();
                                    requestSetting(makeSectionString, null);
                                }
                            }
                            InputHelper.hideSoftInput(editText);
                        })
                        .setNegativeButton(R.string.dialog_btn_cancel, (dialogInterface, i2) -> InputHelper.hideSoftInput(editText));
        mSetNegativeButton.setTitle(R.string.mine_section_setting_dialog_input);
        mSetNegativeButton.show();
        InputHelper.showSoftInput(editText);
    }

    public void updateSections(int index, int section) {
        int[] iArr = sections;
        if (iArr == null) {
            return;
        }
        int i = 1;
        if (iArr.length - 1 == index) {
            int length = iArr.length - 1;
            int i2 = 10;
            while (length > 0) {
                sections[length] = (int) (section * (i2 / 10.0f));
                length--;
                i2--;
            }
        }
        sections[index] = section;
        while (true) {
            int[] iArr2 = sections;
            if (i >= iArr2.length) {
                return;
            }
            restrictSectionValue(i, iArr2[i]);
            i++;
        }
    }

    private void restrictSectionValue(int index, int section) {
        Log.v(TAG, "updateSections, index = " + index + ", section = " + section);
        int[] iArr = sections;
        int i = index == iArr.length + (-1) ? 250 : iArr[index + 1];
        int i2 = iArr[index - 1];
        if (section >= i) {
            section = i - 1;
        } else if (section <= i2) {
            section = i2 + 1;
        }
        iArr[index] = section;
    }

    public String makeSectionString(int[] sections) {
        String str = "";
        for (int i = 0; i < sections.length; i++) {
            str = str + sections[i];
            if (i < sections.length - 1) {
                str = str + ";";
            }
        }
        Log.v(TAG, "makeSectionString, jsonStr = " + str);
        return str;
    }

    public void requestSetting(String jsonStr, Integer hearRateAlert) {
        viewModel.updateSportSetting(App.getContext().getUserId(), new UserSportSetting(null, hearRateAlert, null, null, jsonStr, null));
    }

    public void showZoneInfo(View view) {
        Spanned fromHtml;
        if (Build.VERSION.SDK_INT >= 24) {
            fromHtml = Html.fromHtml(getString(R.string.mine_section_setting_hr_about_zone), 0);
        } else {
            fromHtml = Html.fromHtml(getString(R.string.mine_section_setting_hr_about_zone));
        }
        new BiciAlertDialogBuilder(HeartrateSectionSettingActivity.this).setMessage(fromHtml).show();
    }

    public void setupHeartWarning(View view) {
        if (alertValue != 0) {
            showEditDialog(-1, String.valueOf(alertValue));
            return;
        }
        showEditDialog(-1, String.valueOf(RemoteSharedPreference.getInstance().getHeartRateWarningValue()));
    }

}
